package cn.itcast.orders.service.impl;

import cn.itcast.cart.dto.ShoppingCartDTO;
import cn.itcast.cart.feign.ShoppingCartFeign;
import cn.itcast.cart.pojo.ShoppingCart;
import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.OrderCancellationConstant;
import cn.itcast.context.BaseContext;
import cn.itcast.exception.OrderBusinessException;
import cn.itcast.orders.dto.OrdersCancelDTO;
import cn.itcast.orders.dto.OrdersPageQueryDTO;
import cn.itcast.orders.dto.OrdersPaymentDTO;
import cn.itcast.orders.dto.OrdersSubmitDTO;
import cn.itcast.orders.mapper.AddressBookMapper;
import cn.itcast.orders.mapper.OrderDetailMapper;
import cn.itcast.orders.mapper.OrderMapper;
import cn.itcast.orders.pojo.*;
import cn.itcast.orders.service.OrderService;
import cn.itcast.orders.vo.OrderPaymentVO;
import cn.itcast.orders.vo.OrderStatisticsVO;
import cn.itcast.orders.vo.OrderSubmitVO;
import cn.itcast.orders.vo.OrderVO;
import cn.itcast.result.PageBean;
import cn.itcast.result.Result;
import cn.itcast.users.feign.UserFegin;
import cn.itcast.users.pojo.User;
import cn.itcast.utils.BaiduUtil;
import cn.itcast.utils.WeChatPayUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
//    @Autowired
//    private ShoppingCartService shoppingCartService;

    @Autowired
    private ShoppingCartFeign shoppingCartFeign;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduUtil baiduUtil;

    @Autowired
    private UserFegin userFegin;

    /**
     * 用户催单
     *
     * @param id
     */
//    @Autowired
//    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Override
    public OrderSubmitVO getOrderSubmit(OrdersSubmitDTO dto) {
        //准备数据
        //地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId().intValue());
        Double distance = baiduUtil.getDistance(baiduUtil.getCoordinate(addressBook.getProvinceName() +
                addressBook.getCityName() +
                addressBook.getDistrictName() +
                addressBook.getDetail()
        ));
        log.info("配送距离：{}km", distance / 1000);
        if (BigDecimal.valueOf(distance).compareTo(new BigDecimal(5000.0)) > 0) {
            throw new OrderBusinessException(MessageConstant.DELIVERY_DISTANCE_TOO_FAR_ORDER_FAILED);
        }

        //购物车信息
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list();
        Result<List<ShoppingCart>> search = shoppingCartFeign.search(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        List<ShoppingCart> shoppingCarts = search.getData();

        //将订单数据写入数据库
        Orders order = new Orders();
        BeanUtils.copyProperties(dto, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber("dd" + System.currentTimeMillis());
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        orderMapper.insert(order);


        List<OrderDetail> orderDetails = shoppingCarts.stream().map(cart -> {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(cart, detail);
            detail.setOrderId(order.getId());
            return detail;
        }).collect(Collectors.toList());
        orderDetailMapper.insters(orderDetails);

        //清空购物车
//        shoppingCartService.cleanShoppingCart();
        shoppingCartFeign.remoteClean(BaseContext.getCurrentId());

        //消息提醒
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("type",1);
//        jsonObject.put("orderId",order.getId());
//        jsonObject.put("content","订单号：" + order.getNumber());
//        webSocketServer.sendToAllClient(jsonObject.toJSONString());

        //将订单数据封装返回
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
        Result<User> result = userFegin.one(userId);
        User user = result.getData();

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageBean getHistoricalOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setUserId(BaseContext.getCurrentId());

        dto.setUserId(BaseContext.getCurrentId());
        List<HistoricalOrders> page = orderMapper.getHistoricalOrders(dto);
//        PageInfo<HistoricalOrders> historicalOrdersPageInfo = new PageInfo<>(page);
//        return new PageBean(historicalOrdersPageInfo.getSize(), historicalOrdersPageInfo.getList());
        return new PageBean(page.size(), page);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public HistoricalOrders getOrderDetailById(Integer id) {
        OrdersPageQueryDTO orders = OrdersPageQueryDTO.builder()
                .id(id)
                .build();
        HistoricalOrders historicalOrders = orderMapper.getHistoricalOrders(orders).get(0);

        return historicalOrders;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrderBy(Integer id) {
        //获取订单
        Orders orders = orderMapper.getById(id);

        Integer status = orders.getStatus();
        //如果订单状态为待接单且支付状态为已支付的情况下，还需要进行退款操作
        if (status == Orders.PAID) {
            //进行退款
        }
        //仅取消待付款和待接单状态的订单
        if (status == Orders.PENDING_PAYMENT || status == Orders.TO_BE_CONFIRMED) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(OrderCancellationConstant.USER_CANCELLATION);
            orderMapper.update(orders);
        } else {
            //取消失败
        }

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    @Transactional
    public void oneMoreOrder(Integer id) {
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        orderDetails.forEach(o -> {
            //ShoppingCartDTO要在里面new出来，以避免前一次循环的状态对下一次循环产生影响。
            ShoppingCartDTO shoppingCart = new ShoppingCartDTO();
            BeanUtils.copyProperties(o, shoppingCart);
//            shoppingCartService.addShoppingCart(shoppingCart);
            shoppingCartFeign.add(shoppingCart);

        });
    }

    /**
     * 订单搜索
     *
     * @param dto
     * @return
     */
    @Override
    public PageBean getByconditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<HistoricalOrders> historicalOrders = orderMapper.getHistoricalOrders(dto);
        historicalOrders.forEach(o -> {
            List<OrderDetail> orderDetailList = o.getOrderDetailList();
            if (orderDetailList.size() > 0) {
                String re = new String();
                for (OrderDetail detail : orderDetailList) {
                    re = detail.getName() + "*" + detail.getNumber() + ";";
                    o.setOrderDishes(o.getOrderDishes() == null ? "" : o.getOrderDishes() + re);
                }
            }
        });

        return PageBean.builder()
                .total(historicalOrders.getTotal())
                .records(historicalOrders.getResult())
                .build();
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statisticsOrderStatus() {
        List<OrderStatistics> list = orderMapper.getOrderStatus();

//        OrderStatisticsVO vo = OrderStatisticsVO.builder()
//                .toBeConfirmed(map.get(2))
//                .confirmed(map.get(3))
//                .deliveryInProgress(map.get(4))
//                .build();
        OrderStatisticsVO vo = new OrderStatisticsVO();
        list.forEach(o -> {
            String status = o.getStatus();
            if (status.equals("2")) vo.setToBeConfirmed(o.getCount());//待接单数量
            if (status.equals("3")) vo.setConfirmed(o.getCount());//待派送数量
            if (status.equals("4")) vo.setDeliveryInProgress(o.getCount());//派送中数量
        });

        return vo;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Integer id) {
        Orders orders = Orders.builder()
                .id(id.longValue())
                .build();

        OrderVO orderVO = orderMapper.getByCriteria(orders).get(0);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param id
     */
    @Override
    public void orderConfirm(Integer id) {
        Orders orders = Orders.builder()
                .id(id.longValue())
                .status(3)
                .build();
        orderMapper.update(orders);

        return;
    }

    /**
     * 拒单
     *
     * @param map
     */
    @Override
    public void orderRejection(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        String rejectionReason = map.get("rejectionReason") + "";
        Orders orders = Orders.builder()
                .id(id.longValue())
                .status(6)
                .payStatus(0)
                .cancelTime(LocalDateTime.now())
                .cancelReason(rejectionReason)
                .build();
        orderMapper.update(orders);

        return;
    }

    /**
     * 取消订单
     *
     * @param dto
     */
    @Override
    public void orderCancel(OrdersCancelDTO dto) {
        Orders orders = Orders.builder()
                .id(dto.getId())
                .status(6)
                .payStatus(0)
                .cancelTime(LocalDateTime.now())
                .cancelReason(dto.getCancelReason())
                .build();
        orderMapper.update(orders);

    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void orderdDlivery(Integer id) {
        Orders orders = Orders.builder()
                .id(id.longValue())
                .status(4)
                .build();
        orderMapper.update(orders);

        return;
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void orderdComplete(Integer id) {
        Orders orders = Orders.builder()
                .id(id.longValue())
                .status(5)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 根据状态+时间 查询超时的订单
     *
     * @param status
     * @param time
     * @return
     */
    @Override
    public List<Orders> getTimeOutOrderByStatusAndTime(Integer status, LocalDateTime time) {
        return orderMapper.getTimeOutOrderByStatusAndTime(status, time);

    }

    /**
     * 修改订单
     *
     * @param orders
     */
    @Override
    public void update(Orders orders) {
        orderMapper.update(orders);
    }

    @Override
    public void orderReminder(Long id) {
        Orders orders = orderMapper.getById(id.intValue());


        //利用webSocket进行用户催单
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", 2);
        jsonObject.put("orderId", id);
        jsonObject.put("content", "订单号：" + orders.getNumber());
//        webSocketServer.sendToAllClient(jsonObject.toJSONString());
    }
}